﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Rss.Domain
{

    /// <summary>
    ///作者
    /// </summary>
    public class Author
    {

        #region 属性
        /// <summary>
        /// 编号
        /// </summary>
        public int Id { get; set; }

        /// <summary>
        /// 姓名
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 口号
        /// </summary>
        public string Slogan { get; set; }

        /// <summary>
        /// 简介
        /// </summary>
        public string Profile { get; set; }

        /// <summary>
        /// 聚合
        /// </summary>
        public IEnumerable<RssInfo> Rss { get; set; }

        /// <summary>
        /// 头像
        /// </summary>
        public string Photo { get; set; }
        #endregion 属性

        #region 方法
        /// <summary>
        /// <![CDATA[获取所有作者]]>
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Author> GetAllAuthor()
        {
            string strCacheKey = "__CacheKeyAuthor";
            if (null != System.Web.HttpRuntime.Cache[strCacheKey])
            {
                return (IEnumerable<Author>)System.Web.HttpRuntime.Cache[strCacheKey];
            }
            IEnumerable<Author> result = null;
            string strJsonDataPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config/configuration.json");
            using (FileStream fileStream = new FileStream(strJsonDataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (StreamReader streamReader = new StreamReader(fileStream))
                {
                    string strJsonText = streamReader.ReadToEnd();
                    result = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Author>>(strJsonText);
                    //缓存依赖
                    if (result.Any())
                    {
                        System.Web.HttpRuntime.Cache.Insert(strCacheKey,
                                                            result,
                                                            new System.Web.Caching.CacheDependency(strJsonDataPath),
                                                            DateTime.Now.AddHours(2), System.Web.Caching.Cache.NoSlidingExpiration);
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 根据ID，获取作者信息
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public Author GetAuthorById(int id)
        {
            var all = GetAllAuthor();
            if (all != null && all.Any())
            {
                var author = all.FirstOrDefault(m => m.Id == id);
                return author;
            }
            return null;
        }
        #endregion 方法
    }
}
